package com.cq.androidtools.datastore

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import androidx.datastore.createDataStore
import com.cq.androidtools.protobuf.UserPrefs
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * 作者: CQ
 * 日期: 2021-04-01
 * 说明:
 */
class protoUtil {

    companion object {
        private var dataStore: DataStore<UserPrefs.UserPreferences>? = null
        fun initView(context: Context, name: String, s: Serializer<UserPrefs.UserPreferences>) {
            dataStore = context.createDataStore(
                fileName = name,
                serializer = s
            )
        }
    }

    fun saveData(completed: Boolean) {
        GlobalScope.launch {
            dataStore!!.updateData { preferences ->
                preferences.toBuilder().setShowCompleted(completed).build()
            }
            //4.获取数据
            val getName = dataStore!!.data.map {
                it.showCompleted
            }.collect { //flow 调用collect 开始消费数据
                Log.e("TAG", "onCreate: $it")  //打印出 jackie
            }
        }
    }

}

